package algo.ch0202;

import algo.ch0201.SortAlgorithm;

/**
 * @author mougua
 */
public class Merge extends SortAlgorithm {
    private static Comparable[] aux;

    public static void merge(Comparable[] a, int lo, int mid, int hi) {
        int i = lo, j = mid + 1;
        System.out.println("[merge] lo: " + String.valueOf(lo) +
                ", hi: " + String.valueOf(hi));
        if (hi + 1 - lo >= 0) {
            System.arraycopy(a, lo, aux, lo, hi + 1 - lo);
        }
        for (int k = lo; k <= hi; k++) {
            // 比较aux[i]和aux[j]，取较小值填入a[k],直到其中一边满，余下填入另一边
            if (i > mid) {
                a[k] = aux[j++];
            } else if (j > hi) {
                a[k] = aux[i++];
            } else if (less(aux[j], aux[i])) {
                a[k] = aux[j++];
            } else {
                a[k] = aux[i++];
            }
        }
    }

    private static void sort(Comparable[] a, int lo, int hi) {
        if (hi <= lo) {
            return;
        }
        System.out.println("[sort] lo: " + String.valueOf(lo) +
                ", hi: " + String.valueOf(hi));
        int mid = lo + (hi - lo) / 2;
        sort(a, lo, mid);
        sort(a, mid + 1, hi);
        merge(a, lo, mid, hi);
    }

    public static void sort(Comparable[] a) {
        aux = new Comparable[a.length];
        sort(a, 0, a.length - 1);
    }
}
